<?php
/**
 * @Description: 任教学科
 * @Author: kzj
 * @datetime: 2023-02-24
 */
namespace App\Services\Faculty;

use App\Http\Controllers\Excel\ExcelExport;
use App\Http\Controllers\Excel\ExcelImport;
use App\Models\ActivityInfo;
use App\Models\DictionaryItem;
use App\Models\YxhdInfo;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Facades\Excel;

/**
 * 教师培训 (服务)
 */
class FacultyExportService
{
    /** @var \App\Repositories\System\ActivityRepository $activityRepository */
    private $activityRepository;
    /** @var \App\Repositories\System\ParticipantRepository $participantRepository */
    private $participantRepository;
    /** @var \App\Repositories\System\SystemTaskRepository $systemTaskRepository */
    private $systemTaskRepository;

    public function __construct()
    {
        $this->activityRepository = app('activityRepository');
        $this->participantRepository = app('participantRepository');
        $this->systemTaskRepository = app('systemTaskRepository');
    }

    /*
     * @Description: 开发课程导出
     * @Author:  Kzj
     * @Date: 2023-11-17 14:43:04
     */
    public function exportCourse($request)
    {
        $formKey = NULL;
        $termId = 0;
        $name = '';
        $status = '';
        $hostName = ''; //主持人
        $beginDate = '';
        $endDate = '';
        $joinName = '';
        $creatorName = '';
        $rangeDate = [];
        $jsonSearch = [];
        $hasSearch = false;

        $user = Auth::user();
        $roleType = $user->cur_role_type;
        // dd($roleType);

        $formKey = $request['form_key'] ?? '';
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $hasSearch = true;
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $hasSearch = true;
            $name = $request['search']['name'];
        }
        if (isset($request['search']['status']) && !empty($request['search']['status'])){
            $hasSearch = true;
            $status = $request['search']['status'];
        }
        if (isset($request['search']['host_name']) && !empty($request['search']['host_name'])){
            $hasSearch = true;
            $hostName = $request['search']['host_name'];
        }
        if (isset($request['search']['begin_date']) && !empty($request['search']['begin_date'])){
            $hasSearch = true;
            $beginDate = $request['search']['begin_date'];
        }
        if (isset($request['search']['end_date']) && !empty($request['search']['end_date'])){
            $hasSearch = true;
            $endDate = $request['search']['end_date'];
        }
        //通过json的类型及optionId值进行查询
        if (isset($request['json_search']['pubications_publish_type'] )&& !empty($request['json_search']['pubications_publish_type'])){
            $hasSearch = true;
            $jsonSearch['pubications_publish_type'] = $request['json_search']['pubications_publish_type'];
        }
        if (isset($request['search']['level'] )&& !empty($request['search']['level'])){
            $hasSearch = true;
            $jsonSearch['level'] = $request['search']['level'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $hasSearch = true;
            $jsonSearch['course'] = $request['search']['course'];
        }
        if (isset($request['search']['grade'] )&& !empty($request['search']['grade'])){
            $hasSearch = true;
            $jsonSearch['grade'] = $request['search']['grade'];
        }
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $hasSearch = true;
            $jsonSearch['class_item'] = $request['search']['class_item'];
        }
        if (isset($request['search']['category'] )&& !empty($request['search']['category'])){
            $hasSearch = true;
            $jsonSearch['category'] = $request['search']['category'];
        }
        if (isset($request['search']['reception_class'] )&& !empty($request['search']['reception_class'])){
            $hasSearch = true;
            $jsonSearch['reception_class'] = $request['search']['reception_class'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $hasSearch = true;
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        if (isset($request['search']['join_name'] )&& !empty($request['search']['join_name'])){
            $hasSearch = true;
            $joinName = $request['search']['join_name'];
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $hasSearch = true;
            $creatorName = $request['search']['creator_name'];
        }
        if (!$hasSearch){
            $status = 'PASS';//导出的数据均为审核通过的
        }

        $user = Auth::user();
        $viewAll = $this->activityRepository->getViewPower($request['form_key']);

        $output = ActivityInfo::select('activity_info.*', 'b.status')
            ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->when($formKey, function($q) use($formKey) {
                if(is_array($formKey)) {
                    $q->whereIn('activity_category', $formKey);
                } else {
                    $q->where('activity_category', $formKey);
                }
            })
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('activity_info.data_version_id', $termId);
                });
            })
            ->when($name, function($q) use($name) {
                $q->where('activity_info.name', 'like', '%' . $name . '%');
            })
            ->when($status, function($q) use($status) {
                $q->where('b.status', '=', $status);
            })
            ->when($beginDate, function($q) use($beginDate) {
                $q->where('activity_info.begin_date', '=', $beginDate);
            })
            ->when($endDate, function($q) use($endDate) {
                $q->where('activity_info.end_date', '=', $endDate);
            })
            ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                foreach($jsonSearch as $k => $id) {
                    $q->whereRaw(" JSON_EXTRACT(activity_info.`".$k."`,'$[0].optionId') = $id");
                }
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('activity_info.begin_date', '<=', $rangeDate[0])->where('activity_info.end_date', '>=', $rangeDate[1]);
            })
            ->when($hostName, function($q) use($hostName) {
                $q->whereHas('compereUser', function ($query) use($hostName) {
                    $query->where('nickname', 'like', '%' . $hostName . '%');
                });
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){//处理档案袋只查看自己的数据
                $q->whereHas('participants', function($query) use($request){
                    $query->where('user_id', $request['user_id']);
                });
            })
            ->when(!isset($request['user_id']), function($q) use($user, $viewAll){//处理非档案袋只查看自己的数据
                $q->when(!$viewAll && !$user->is_checker, function($qq) use($user){
                    $qq->whereHas('participants', function($query) use($user){
                        $query->where('user_id', $user->id);
                    });
                });
            })
            ->when($joinName, function($q) use($joinName) {
                $q->whereHas('joinUser', function ($query) use($joinName) {
                    $query->where('nickname', 'like', '%' . $joinName . '%');
                });
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when(!empty($request['search']['materials_date']),function($q) use($request){
                return $q->whereRaw(" activity_info.data_version_id in ({$request['search']['materials_date']})");
            })
            ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'instance:id,status')
            ->where('activity_info.deleted', 0)
            ->orderBy('activity_info.id', 'desc')
            ->get();
            //dd(DB::getQueryLog());
        // dd($output->toArray());

        $title = ['学年学期','课题名称','开始日期','结束日期','级别','主持人','参与人', '创建人', '状态'];
        $exportData = [];
        foreach($output as $k => $v){
            $status = '-';
            $disStatus = $v->instance ? $v['instance']['status'] : '';
            switch($disStatus) {
                case 'REVOKE': $status = '撤回'; break;
                case 'FILL_IN': $status = '未提交'; break;
                case 'REVIEW': $status = '待审核'; break;
                case 'REVIEW_FAIL': $status = '已驳回'; break;
                case 'PASS': $status = '审核通过'; break;
            }

            $compere = $v->compere->map(function ($value, $key) {
                return $value->user && $value->user->nickname ? $value->user->nickname : '';
            });
            $participant = $v->participant->map(function ($value, $key) {
                return $value->user && $value->user->nickname ? $value->user->nickname : '';
            });

            $item = [
                'term' => $v->data_version_id ? $v->term->title : '',
                'name' => $v->name,
                'begin_date' => $v->begin_date,
                'end_date' => $v->end_date,
                'level' => !empty($v->level_array) ? $v['level_array'][0]['selectValue'] : '',
                'compere' => $compere->implode(','),
                'participant' => $participant->implode(','),
                'creator' => !empty($v->creator) ? $v->creator->nickname : '',
                'status' => $status
            ];

            $exportData[] = $item;
        }
        array_unshift($exportData, $title);

        $fileName = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($exportData), $fileName, 'excel');

        $result['file_name'] = $fileName;

        return $result;
    }

    /*
     * @Description: 参与教研导出
     * @Author:  Kzj
     * @Date: 2023-11-17 14:43:04
     */
    public function exportResearch($request)
    {
        $formKey = NULL;
        $termId = 0;
        $name = '';
        $status = '';
        $hostName = ''; //主持人
        $beginDate = '';
        $endDate = '';
        $joinName = '';
        $creatorName = '';
        $rangeDate = [];
        $jsonSearch = [];
        $hasSearch = false;

        $user = Auth::user();
        $roleType = $user->cur_role_type;
        // dd($roleType);

        $formKey = $request['form_key'] ?? '';
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $hasSearch = true;
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $hasSearch = true;
            $name = $request['search']['name'];
        }
        if (isset($request['search']['status']) && !empty($request['search']['status'])){
            $hasSearch = true;
            $status = $request['search']['status'];
        }
        if (isset($request['search']['host_name']) && !empty($request['search']['host_name'])){
            $hasSearch = true;
            $hostName = $request['search']['host_name'];
        }
        if (isset($request['search']['begin_date']) && !empty($request['search']['begin_date'])){
            $hasSearch = true;
            $beginDate = $request['search']['begin_date'];
        }
        if (isset($request['search']['end_date']) && !empty($request['search']['end_date'])){
            $hasSearch = true;
            $endDate = $request['search']['end_date'];
        }
        //通过json的类型及optionId值进行查询
        if (isset($request['json_search']['pubications_publish_type'] )&& !empty($request['json_search']['pubications_publish_type'])){
            $hasSearch = true;
            $jsonSearch['pubications_publish_type'] = $request['json_search']['pubications_publish_type'];
        }
        if (isset($request['search']['level'] )&& !empty($request['search']['level'])){
            $hasSearch = true;
            $jsonSearch['level'] = $request['search']['level'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $hasSearch = true;
            $jsonSearch['course'] = $request['search']['course'];
        }
        if (isset($request['search']['grade'] )&& !empty($request['search']['grade'])){
            $hasSearch = true;
            $jsonSearch['grade'] = $request['search']['grade'];
        }
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $hasSearch = true;
            $jsonSearch['class_item'] = $request['search']['class_item'];
        }
        if (isset($request['search']['category'] )&& !empty($request['search']['category'])){
            $hasSearch = true;
            $jsonSearch['category'] = $request['search']['category'];
        }
        if (isset($request['search']['reception_class'] )&& !empty($request['search']['reception_class'])){
            $hasSearch = true;
            $jsonSearch['reception_class'] = $request['search']['reception_class'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $hasSearch = true;
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        if (isset($request['search']['join_name'] )&& !empty($request['search']['join_name'])){
            $hasSearch = true;
            $joinName = $request['search']['join_name'];
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $hasSearch = true;
            $creatorName = $request['search']['creator_name'];
        }
        if (!$hasSearch){
            $status = 'PASS';//导出的数据均为审核通过的
        }

        $user = Auth::user();
        $viewAll = $this->activityRepository->getViewPower($request['form_key']);

        $output = ActivityInfo::select('activity_info.*', 'b.status')
            ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->when($formKey, function($q) use($formKey) {
                if(is_array($formKey)) {
                    $q->whereIn('activity_category', $formKey);
                } else {
                    $q->where('activity_category', $formKey);
                }
            })
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('activity_info.data_version_id', $termId);
                });
            })
            ->when($name, function($q) use($name) {
                $q->where('activity_info.name', 'like', '%' . $name . '%');
            })
            ->when($status, function($q) use($status) {
                $q->where('b.status', '=', $status);
            })
            ->when($beginDate, function($q) use($beginDate) {
                $q->where('activity_info.begin_date', '=', $beginDate);
            })
            ->when($endDate, function($q) use($endDate) {
                $q->where('activity_info.end_date', '=', $endDate);
            })
            ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                foreach($jsonSearch as $k => $id) {
                    $q->whereRaw(" JSON_EXTRACT(activity_info.`".$k."`,'$[0].optionId') = $id");
                }
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('activity_info.begin_date', '<=', $rangeDate[0])->where('activity_info.end_date', '>=', $rangeDate[1]);
            })
            ->when($hostName, function($q) use($hostName) {
                $q->whereHas('compereUser', function ($query) use($hostName) {
                    $query->where('nickname', 'like', '%' . $hostName . '%');
                });
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){//处理档案袋只查看自己的数据
                $q->whereHas('participants', function($query) use($request){
                    $query->where('user_id', $request['user_id']);
                });
            })
            ->when(!isset($request['user_id']), function($q) use($user, $viewAll){//处理非档案袋只查看自己的数据
                $q->when(!$viewAll && !$user->is_checker, function($qq) use($user){
                    $qq->whereHas('participants', function($query) use($user){
                        $query->where('user_id', $user->id);
                    });
                });
            })
            ->when($joinName, function($q) use($joinName) {
                $q->whereHas('joinUser', function ($query) use($joinName) {
                    $query->where('nickname', 'like', '%' . $joinName . '%');
                });
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when(!empty($request['search']['materials_date']),function($q) use($request){
                return $q->whereRaw(" activity_info.data_version_id in ({$request['search']['materials_date']})");
            })
            ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'instance:id,status')
            ->where('activity_info.deleted', 0)
            ->orderBy('activity_info.id', 'desc')
            ->get();
            //dd(DB::getQueryLog());
        // dd($output->toArray());

        $title = ['学年学期','教研名称','日期','级别','学科','年级','主持人','创建人','状态'];
        $exportData = [];
        foreach($output as $k => $v){
            $status = '-';
            $disStatus = $v->instance ? $v['instance']['status'] : '';
            switch($disStatus) {
                case 'REVOKE': $status = '撤回'; break;
                case 'FILL_IN': $status = '未提交'; break;
                case 'REVIEW': $status = '待审核'; break;
                case 'REVIEW_FAIL': $status = '已驳回'; break;
                case 'PASS': $status = '审核通过'; break;
            }

            $item = [
                'term' => $v->data_version_id ? $v->term->title : '',
                'name' => $v->name,
                'date' => $v->begin_date,
                'level' => !empty($v->level_array) ? $v['level_array'][0]['selectValue'] : '',
                'course' => !empty($v->course_set) ? $v['course_set'][0]['selectValue'] : '',
                'grade' => !empty($v->grade_array) ? $v['grade_array'][0]['selectValue'] : '',
                'teacher_name' => $v->teacher_name,
                'creator' => !empty($v->creator) ? $v->creator->nickname : '',
                'status' => $status
            ];

            $exportData[] = $item;
        }
        array_unshift($exportData, $title);

        $fileName = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($exportData), $fileName, 'excel');

        $result['file_name'] = $fileName;

        return $result;
    }

    /*
     * @Description: 外出培训导出
     * @Author:  Kzj
     * @Date: 2023-11-17 14:43:04
     */
    public function exportOutraining($request)
    {
        $formKey = NULL;
        $termId = 0;
        $name = '';
        $status = '';
        $hostName = ''; //主持人
        $beginDate = '';
        $endDate = '';
        $joinName = '';
        $creatorName = '';
        $rangeDate = [];
        $jsonSearch = [];
        $hasSearch = false;

        $user = Auth::user();
        $roleType = $user->cur_role_type;
        // dd($roleType);

        $formKey = $request['form_key'] ?? '';
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $hasSearch = true;
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $hasSearch = true;
            $name = $request['search']['name'];
        }
        if (isset($request['search']['status']) && !empty($request['search']['status'])){
            $hasSearch = true;
            $status = $request['search']['status'];
        }
        if (isset($request['search']['host_name']) && !empty($request['search']['host_name'])){
            $hasSearch = true;
            $hostName = $request['search']['host_name'];
        }
        if (isset($request['search']['begin_date']) && !empty($request['search']['begin_date'])){
            $hasSearch = true;
            $beginDate = $request['search']['begin_date'];
        }
        if (isset($request['search']['end_date']) && !empty($request['search']['end_date'])){
            $hasSearch = true;
            $endDate = $request['search']['end_date'];
        }
        //通过json的类型及optionId值进行查询
        if (isset($request['json_search']['pubications_publish_type'] )&& !empty($request['json_search']['pubications_publish_type'])){
            $hasSearch = true;
            $jsonSearch['pubications_publish_type'] = $request['json_search']['pubications_publish_type'];
        }
        if (isset($request['search']['level'] )&& !empty($request['search']['level'])){
            $hasSearch = true;
            $jsonSearch['level'] = $request['search']['level'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $hasSearch = true;
            $jsonSearch['course'] = $request['search']['course'];
        }
        if (isset($request['search']['grade'] )&& !empty($request['search']['grade'])){
            $hasSearch = true;
            $jsonSearch['grade'] = $request['search']['grade'];
        }
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $hasSearch = true;
            $jsonSearch['class_item'] = $request['search']['class_item'];
        }
        if (isset($request['search']['category'] )&& !empty($request['search']['category'])){
            $hasSearch = true;
            $jsonSearch['category'] = $request['search']['category'];
        }
        if (isset($request['search']['reception_class'] )&& !empty($request['search']['reception_class'])){
            $hasSearch = true;
            $jsonSearch['reception_class'] = $request['search']['reception_class'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $hasSearch = true;
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        if (isset($request['search']['join_name'] )&& !empty($request['search']['join_name'])){
            $hasSearch = true;
            $joinName = $request['search']['join_name'];
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $hasSearch = true;
            $creatorName = $request['search']['creator_name'];
        }
        if (!$hasSearch){
            $status = 'PASS';//导出的数据均为审核通过的
        }

        $user = Auth::user();
        $viewAll = $this->activityRepository->getViewPower($request['form_key']);

        $output = ActivityInfo::select('activity_info.*', 'b.status')
            ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->when($formKey, function($q) use($formKey) {
                if(is_array($formKey)) {
                    $q->whereIn('activity_category', $formKey);
                } else {
                    $q->where('activity_category', $formKey);
                }
            })
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('activity_info.data_version_id', $termId);
                });
            })
            ->when($name, function($q) use($name) {
                $q->where('activity_info.name', 'like', '%' . $name . '%');
            })
            ->when($status, function($q) use($status) {
                $q->where('b.status', '=', $status);
            })
            ->when($beginDate, function($q) use($beginDate) {
                $q->where('activity_info.begin_date', '=', $beginDate);
            })
            ->when($endDate, function($q) use($endDate) {
                $q->where('activity_info.end_date', '=', $endDate);
            })
            ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                foreach($jsonSearch as $k => $id) {
                    $q->whereRaw(" JSON_EXTRACT(activity_info.`".$k."`,'$[0].optionId') = $id");
                }
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('activity_info.begin_date', '<=', $rangeDate[0])->where('activity_info.end_date', '>=', $rangeDate[1]);
            })
            ->when($hostName, function($q) use($hostName) {
                $q->whereHas('compereUser', function ($query) use($hostName) {
                    $query->where('nickname', 'like', '%' . $hostName . '%');
                });
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){//处理档案袋只查看自己的数据
                $q->whereHas('participants', function($query) use($request){
                    $query->where('user_id', $request['user_id']);
                });
            })
            ->when(!isset($request['user_id']), function($q) use($user, $viewAll){//处理非档案袋只查看自己的数据
                $q->when(!$viewAll && !$user->is_checker, function($qq) use($user){
                    $qq->whereHas('participants', function($query) use($user){
                        $query->where('user_id', $user->id);
                    });
                });
            })
            ->when($joinName, function($q) use($joinName) {
                $q->whereHas('joinUser', function ($query) use($joinName) {
                    $query->where('nickname', 'like', '%' . $joinName . '%');
                });
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when(!empty($request['search']['materials_date']),function($q) use($request){
                return $q->whereRaw(" activity_info.data_version_id in ({$request['search']['materials_date']})");
            })
            ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'instance:id,status')
            ->where('activity_info.deleted', 0)
            ->orderBy('activity_info.id', 'desc')
            ->get();
            //dd(DB::getQueryLog());
        // dd($output->toArray());

        $title = ['学年学期','名称','开始日期','结束日期','级别','主持人','创建人','状态'];
        $exportData = [];
        foreach($output as $k => $v){
            $status = '-';
            $disStatus = $v->instance ? $v['instance']['status'] : '';
            switch($disStatus) {
                case 'REVOKE': $status = '撤回'; break;
                case 'FILL_IN': $status = '未提交'; break;
                case 'REVIEW': $status = '待审核'; break;
                case 'REVIEW_FAIL': $status = '已驳回'; break;
                case 'PASS': $status = '审核通过'; break;
            }

            $compere = $v->compere->map(function ($value, $key) {
                return $value->user->nickname ? $value->user->nickname : '';
            });

            $item = [
                'term' => $v->data_version_id ? $v->term->title : '',
                'name' => $v->name,
                'begin_date' => $v->begin_date,
                'end_date' => $v->end_date,
                'level' => !empty($v->level_array) ? $v['level_array'][0]['selectValue'] : '',
                'compere' => $compere->implode(','),
                'creator' => !empty($v->creator) ? $v->creator->nickname : '',
                'status' => $status
            ];

            $exportData[] = $item;
        }
        array_unshift($exportData, $title);

        $fileName = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($exportData), $fileName, 'excel');

        $result['file_name'] = $fileName;

        return $result;
    }


    /*
     * @Description: 教师培训其他数据导出
     * @Author:  Kzj
     * @Date: 2023-11-17 14:43:04
     */
    public function exportOther($request)
    {
        $formKey = NULL;
        $termId = 0;
        $name = '';
        $status = '';
        $hostName = ''; //主持人
        $beginDate = '';
        $endDate = '';
        $joinName = '';
        $creatorName = '';
        $rangeDate = [];
        $jsonSearch = [];
        $hasSearch = false;

        $user = Auth::user();
        $roleType = $user->cur_role_type;
        // dd($roleType);

        $formKey = $request['form_key'] ?? '';
        if (isset($request['search']['data_version_id'] )&& !empty($request['search']['data_version_id'])){
            $hasSearch = true;
            $termId = $request['search']['data_version_id'];
        }
        if (isset($request['search']['name']) && !empty($request['search']['name'])){
            $hasSearch = true;
            $name = $request['search']['name'];
        }
        if (isset($request['search']['status']) && !empty($request['search']['status'])){
            $hasSearch = true;
            $status = $request['search']['status'];
        }
        if (isset($request['search']['host_name']) && !empty($request['search']['host_name'])){
            $hasSearch = true;
            $hostName = $request['search']['host_name'];
        }
        if (isset($request['search']['begin_date']) && !empty($request['search']['begin_date'])){
            $hasSearch = true;
            $beginDate = $request['search']['begin_date'];
        }
        if (isset($request['search']['end_date']) && !empty($request['search']['end_date'])){
            $hasSearch = true;
            $endDate = $request['search']['end_date'];
        }
        //通过json的类型及optionId值进行查询
        if (isset($request['json_search']['pubications_publish_type'] )&& !empty($request['json_search']['pubications_publish_type'])){
            $hasSearch = true;
            $jsonSearch['pubications_publish_type'] = $request['json_search']['pubications_publish_type'];
        }
        if (isset($request['search']['level'] )&& !empty($request['search']['level'])){
            $hasSearch = true;
            $jsonSearch['level'] = $request['search']['level'];
        }
        if (isset($request['search']['course'] )&& !empty($request['search']['course'])){
            $hasSearch = true;
            $jsonSearch['course'] = $request['search']['course'];
        }
        if (isset($request['search']['grade'] )&& !empty($request['search']['grade'])){
            $hasSearch = true;
            $jsonSearch['grade'] = $request['search']['grade'];
        }
        if (isset($request['search']['class_item'] )&& !empty($request['search']['class_item'])){
            $hasSearch = true;
            $jsonSearch['class_item'] = $request['search']['class_item'];
        }
        if (isset($request['search']['category'] )&& !empty($request['search']['category'])){
            $hasSearch = true;
            $jsonSearch['category'] = $request['search']['category'];
        }
        if (isset($request['search']['reception_class'] )&& !empty($request['search']['reception_class'])){
            $hasSearch = true;
            $jsonSearch['reception_class'] = $request['search']['reception_class'];
        }
        if (isset($request['search']['date_range'] )&& !empty($request['search']['date_range'])){
            $hasSearch = true;
            $rangeDate = explode(' - ', $request['search']['date_range']);
        }
        if (isset($request['search']['join_name'] )&& !empty($request['search']['join_name'])){
            $hasSearch = true;
            $joinName = $request['search']['join_name'];
        }
        if (isset($request['search']['creator_name'] )&& !empty($request['search']['creator_name'])){
            $hasSearch = true;
            $creatorName = $request['search']['creator_name'];
        }
        if (!$hasSearch){
            $status = 'PASS';//导出的数据均为审核通过的
        }

        $user = Auth::user();
        $viewAll = $this->activityRepository->getViewPower($request['form_key']);

        $output = ActivityInfo::select('activity_info.*', 'b.status')
            ->leftJoin('form_instance as b' ,'activity_info.form_instance_id','=','b.id')
            ->when($formKey, function($q) use($formKey) {
                if(is_array($formKey)) {
                    $q->whereIn('activity_category', $formKey);
                } else {
                    $q->where('activity_category', $formKey);
                }
            })
            ->when($termId > 0, function($q) use($termId) {
                $q->whereHas('term', function ($query) use($termId) {
                    $query->where('activity_info.data_version_id', $termId);
                });
            })
            ->when($name, function($q) use($name) {
                $q->where('activity_info.name', 'like', '%' . $name . '%');
            })
            ->when($status, function($q) use($status) {
                $q->where('b.status', '=', $status);
            })
            ->when($beginDate, function($q) use($beginDate) {
                $q->where('activity_info.begin_date', '=', $beginDate);
            })
            ->when($endDate, function($q) use($endDate) {
                $q->where('activity_info.end_date', '=', $endDate);
            })
            ->when(!empty($jsonSearch), function($q) use($jsonSearch) {
                foreach($jsonSearch as $k => $id) {
                    $q->whereRaw(" JSON_EXTRACT(activity_info.`".$k."`,'$[0].optionId') = $id");
                }
            })
            ->when(!empty($rangeDate), function($q) use($rangeDate) {
                $q->where('activity_info.begin_date', '<=', $rangeDate[0])->where('activity_info.end_date', '>=', $rangeDate[1]);
            })
            ->when($hostName, function($q) use($hostName) {
                $q->whereHas('compereUser', function ($query) use($hostName) {
                    $query->where('nickname', 'like', '%' . $hostName . '%');
                });
            })
            ->when(isset($request['user_id']) && !empty($request['user_id']), function($q) use($request){//处理档案袋只查看自己的数据
                $q->whereHas('participants', function($query) use($request){
                    $query->where('user_id', $request['user_id']);
                });
            })
            ->when(!isset($request['user_id']), function($q) use($user, $viewAll){//处理非档案袋只查看自己的数据
                $q->when(!$viewAll && !$user->is_checker, function($qq) use($user){
                    $qq->whereHas('participants', function($query) use($user){
                        $query->where('user_id', $user->id);
                    });
                });
            })
            ->when($joinName, function($q) use($joinName) {
                $q->whereHas('joinUser', function ($query) use($joinName) {
                    $query->where('nickname', 'like', '%' . $joinName . '%');
                });
            })
            ->when($creatorName, function($q) use($creatorName) {
                $q->whereHas('creator', function ($query) use($creatorName) {
                    $query->where('nickname', 'like', '%' . $creatorName . '%');
                });
            })
            ->when(!empty($request['search']['materials_date']),function($q) use($request){
                return $q->whereRaw(" activity_info.data_version_id in ({$request['search']['materials_date']})");
            })
            ->with('term', 'forminstance', 'compere', 'participant', 'creator', 'instance:id,status')
            ->where('activity_info.deleted', 0)
            ->orderBy('activity_info.id', 'desc')
            ->get();
            //dd(DB::getQueryLog());
        // dd($output->toArray());

        $title = ['学年学期','名称','开始日期','结束日期','类型','级别','学科','主持人','创建人','状态'];
        $exportData = [];
        foreach($output as $k => $v){
            $status = '-';
            $disStatus = $v->instance ? $v['instance']['status'] : '';
            switch($disStatus) {
                case 'REVOKE': $status = '撤回'; break;
                case 'FILL_IN': $status = '未提交'; break;
                case 'REVIEW': $status = '待审核'; break;
                case 'REVIEW_FAIL': $status = '已驳回'; break;
                case 'PASS': $status = '审核通过'; break;
            }

            $compere = $v->compere->map(function ($value, $key) {
                return $value->user->nickname ? $value->user->nickname : '';
            });

            $item = [
                'term' => $v->data_version_id ? $v->term->title : '',
                'name' => $v->name,
                'begin_date' => $v->begin_date,
                'end_date' => $v->end_date,
                'category' => !empty($v->category_array) ? $v['category_array'][0]['selectValue'] : '',
                'level' => !empty($v->level_array) ? $v['level_array'][0]['selectValue'] : '',
                'course' => !empty($v->course_set) ? $v['course_set'][0]['selectValue'] : '',
                'compere' => $compere->implode(','),
                'creator' => !empty($v->creator) ? $v->creator->nickname : '',
                'status' => $status
            ];

            $exportData[] = $item;
        }
        array_unshift($exportData, $title);

        $fileName = md5(auth()->user()->id.time()).'.xlsx';
        Excel::store(new ExcelExport($exportData), $fileName, 'excel');

        $result['file_name'] = $fileName;

        return $result;
    }

    public function getList($request)
    {

        $page = $request['page'] ?? 1;
        $limit = $request['limit'] ?? 10;
        // dd($request, 1);

        $filters = [];
        if (!empty($request['search']['user_name'])){
            $filters[] = ['user_name', 'like', '%'.$request['search']['user_name'].'%'];
        }
        if (!empty($request['search']['course_name'])){
            $filters[] = ['course_name', 'like', '%'.$request['search']['course_name'].'%'];
        }
        if (!empty($request['search']['course_level'])){
            $filters[] = ['course_level', $request['search']['course_level']];
        }

        $user = Auth::user();

        $result = YxhdInfo::query()
//            ->with('user:id,nickname')
            ->when(!empty($filters), function($q) use($filters) {
                $q->where($filters);
            })
            ->paginate($limit, '*', 'page', $page)
            ->toArray();

        return $result;
    }
}
